package com.gmcloud.common.security.config;

import cn.hutool.core.text.CharSequenceUtil;
import com.gmcloud.common.core.constant.SecurityConstants;
import com.gmcloud.common.security.annotation.Inner;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.access.AccessDeniedException;

import javax.servlet.http.HttpServletRequest;

/**
 * 资源放行注解逻辑
 * @author zl.sir
 * @version 1.0
 * @since 2022/8/27 0:48
 */
@Aspect
public class GmSecurityInnerAspect implements Ordered {

    private static final Logger LOGGER = LoggerFactory.getLogger(GmSecurityInnerAspect.class);
    private final HttpServletRequest request;

    public GmSecurityInnerAspect(HttpServletRequest request) {
        this.request = request;
    }

    @Around("@within(inner) || @annotation(inner)")
    public Object around(ProceedingJoinPoint point, Inner inner) throws Throwable {
        // 实际注入的inner实体由表达式后一个注解决定，即是方法上的@Inner注解实体，若方法上无@Inner注解，则获取类上的
        if (inner == null) {
            Class<?> clazz = point.getTarget().getClass();
            inner = AnnotationUtils.findAnnotation(clazz, Inner.class);
        }
        String from = request.getHeader(SecurityConstants.FROM);
        if ((inner != null && inner.value()) && !CharSequenceUtil.equals(SecurityConstants.FROM_IN, from)) {
            LOGGER.warn("访问接口 {} 没有权限", point.getSignature().getName());
            throw new AccessDeniedException("访问权限不足");
        }
        return point.proceed();
    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
